<?php

namespace App\Services\Infra;

use App\Models\AdminInfo;
use App\Models\Device;
use App\Models\UserInfo;
use App\Models\User;
use App\Models\WxUser;
use App\Exceptions\UserException;
use Cache;
use Carbon\Carbon;
use DB;
use Exception;
use Illuminate\Database\QueryException;
use Sentinel;

class UserManager
{

    /**
     * 增加微信用户 openid 记录
     * @param [type] $data 
     */
    public function addWxUser($data)
    {
        try{
    	    WxUser::create($data);
        }catch(Exception $e){
            throw new UserException('addWxUser');
        }
    }

    public function addUserInfo($data)
    {
        try{
            $userInfo = UserInfo::where('user_id', $data['user_id'])->first();
            if(is_null($userInfo))
            {
                UserInfo::create($data);
            }else{
                $userInfo->update($data);
            }
        }catch(Exception $e){
            throw new UserException('addUserInfo');
        }
    }

    public function addAdminInfo($data){
        try{
            AdminInfo::create($data);
        }catch(Exception $e){
            throw new UserException('addAdminInfo');
        }
    }

    /**
     * 获取用户
     * @return [type]
     */
    public function getWxUser()
    {
    	$user = Sentinel::getUser();

        if(is_null($user))
        {
            throw new UserException('notFound');
        }
        $wxUser = WxUser::where('user_id', $user->id)->select(['user_id', 'open_id', 'current_device_code'])->first();
        
	    if(is_null($wxUser))
	    {
            Sentinel::logout();
	 	    throw new UserException('notFound');
	    }
        Cache::put($user->open_id, $wxUser, Carbon::now()->addMinutes(env('CACHE_USER_TIME', 1)));
	    return $wxUser;
    }

    public function getWxUserById($id)
    {
        $wxUser = WxUser::where('user_id', $id)->first();
        if(is_null($wxUser))
        {
            throw new UserException('notFound');
        }
        return $wxUser;
    }

    /**
     * 更新用户所控制设备
     * @param object $wxUser     WxUser 对象
     * @param string $deviceCode 设备编码
     */
    public function updateCurrentDevice($wxUser, $deviceCode)
    {
        $result = $wxUser->update(['current_device_code' => $deviceCode]);
        
        if(!$result)
        {
            throw new UserException('update');
        }
    }

    /**
     * 更新用户
     * @param string $deviceCode 设备编码
     */
    public function updateAll($deviceCode, $newDeviceCode)
    {
		try{
            $result = WxUser::where('current_device_code', $deviceCode)->update(['current_device_code' => $newDeviceCode]);
        }catch(Exception $e){
		    throw new UserException('update');
        }
    }

    /**
     * 根据设备码获取微信用户
     * @param  [type] $deviceCode 
     * @return [type]             
     */
    public function getWxUserByDeviceCode($deviceCode)
    {
        $device = Device::where('code', $deviceCode)->first();
        if(!is_null($device))
        {
            return $device->wxUsers;
        }
    }

    /**
     * 增加用户
     * @param [type] $data 
     */
    public function addUser($data)
    {
        return Sentinel::register($data, true);
    }

    /**
     * 更新管理员信息
     * @param  [type] $userId 
     * @param  [type] $data   
     * @return [type]         
     */
    public function updateAdminInfo($userId, $data)
    {
        $adminInfo = AdminInfo::where('user_id', $userId)->first();
        if(is_null($adminInfo))
        {
            $createData = array_merge(['user_id' => $userId], $data);
            $result = AdminInfo::create($createData);
        }else{
            $result = $adminInfo->update($data);
        }
        if(!$result)
        {
            throw new UserException('updateAdminInfo');
        }
    }

    /**
     * 根据 open_id 查找微信用户
     * @param  [type] $openId
     * @return [type]           
     */
    public function findWxUserByOpenId($openId)
    {
        $query = WxUser::where('open_id', 'like', '%'.$openId.'%');
        return $query;
    }

    /**
     * 获取全部管理员信息
     * @return [type] 
     */
    public function getAllAdminInfo()
    {
        return User::with(['adminInfo' => function($query){
                    $query->select(['user_id', 'name', 'phone', 'sex']);
                }])->where('is_admin', 1)->select(['id', 'username'])->paginate(8);
    }

    /**
     * 根据 id 获取用户
     * @param  [type] $id 
     * @return [type]     
     */
    public function getUserById($id)
    {
        $user = User::find($id);
        if(is_null($user))
        {
            throw new UserException('notFound');
        }
        return $user;
    }
    
    public function getWxUserByOpenId($openId)
    {
        return WxUser::where('open_id', $openId)->first();
    }

    public function getAllUserInfo()
    {
        return UserInfo::select();
    }


}
